<template>
	<!-- <view class="main-class"> -->
	<z-paging ref="paging" v-model="orderData" @query="queryList" >
		<template #top>	
			<tn-sticky>
				<view class="header-class tn-flex justify-end" >
					<view class="status_bar" style="height: var(--status-bar-height); width: 100%; "></view>			
					<!-- <view class="tn-color-black_text tn-flex justify-between tn-text-xl tn-pl-xl tn-pr-xl tn-pb-xl" >
						<tn-icon name="title" size="1"/>
						<span class="tn-white_text">密码修改</span>
						<tn-icon name="title" size="1" />
					</view> -->
					<tn-navbar height="45px" home-icon="" :bottom-shadow = "false" bg-color="tn-type-primary_bg" text-color="tn-white">已配送任务 </tn-navbar>
				<tn-search-box
					v-model="searchValue"
					@input="searchInputEvent"
					@search="searchBtnClickEventPage"
					size="sm"
					placeholder="搜索关键词,检索客户"
					placeholder-icon="search"
					border-color="#FFFFFF"
					text-color="#FFFFFF"
					placeholder-color="#FFFFFF"
					class="search-class tn-m-sm tn-text-bold"
					search-button-bg-color="#6bb7ec"
					shape="round"
					/>
				</view>
				
				<view class="tn-p tn-text-xl tn-white_bg" @click="openCalendarPopup">
					日期范围：{{dataInfo.startDate}} 至 {{dataInfo.endDate}}
				</view>
			</tn-sticky>
		</template>
		<hr/>
		<view class="tn-pl tn-pr tn-radius tn-pb">
			<view class="tn-shadow-md tn-pl-sm tn-pt-sm tn-pb-sm"  v-for="(item, index) in orderData">
				<view class="tn-flex-row tn-pt-xs" @click="toNavigate(item)">
					<view class="tn-text-xl tn-text-ellipsis-2 tn-pr-xs tn-text-bold">
						{{item.billcodeinfo}}
					</view>
				</view>
				
				<view class="tn-w-3-4 tn-text-xl tn-text-ellipsis-2 tn-pt-xs tn-red_text tn-text-bold" @click="toNavigate(item)">
					{{item.paytype}}
				</view>
				<view class="tn-flex-row tn-pt-xs" @click="toNavigate(item)">
					<view class="tn-w-3-4 tn-text-xl tn-text-ellipsis-2 tn-pr-xs">
						{{item.businessname}}
					</view>
					<view class="tn-w-1-4 tn-red_text tn-text-xl tn-text-bold">
						{{item.orderstate}}
					</view>	
				</view>
				<view class="tn-pt-xs" @click="toNavigate(item)">
					{{item.address}}
				</view>
				<view class="tn-pt-xs tn-flex-row" @click="toNavigate(item)">
					<view class="tn-w-1-2">
						{{item.areaname}}
					</view>	
					<view class="tn-w-1-2">
						{{item.dates}}
					</view>
				</view>
				<view class="tn-pt-xs tn-flex-row" @click="toNavigate(item)">
					<view class="tn-w-1-2 tn-text-xl tn-red_text">
						{{item.tasknum}}
					</view>
					<view class="tn-w-1-2 tn-red_text tn-text-xl">
						{{item.taxamount}}
					</view>	
				</view>
				<view class="tn-pt-xs" @click="toNavigate(item)">
					{{item.remark}}
				</view>
				
				
			</view>
			<!-- <view class="no-data-class tn-flex tn-flex-column" v-if="orderData.length===0">
				  <tn-empty mode="order" color="tn-gray-dark" size="xl" class="tn-p-xl">
					    <template #tips>暂无订单数据</template>
				  </tn-empty>
			</view> -->
		</view>
	</z-paging>	
	<!-- </view> -->
	
	<!--  -->
	
	<tn-popup v-model="showCalendarPopup" open-direction="top" class="popup-class">
	  <!-- <view class="tn-pt"> -->
	    <tn-calendar v-model="selectDate" min-date="2024-01-01" mode="range" class="calendar-class"/>
	  <!-- </view> -->
	  
	  <view class="tn-mt tn-w-full tn-pb">
	    <tn-button
	      font-size="36"
	      custom-class="popup-calendar-button"
	      @click="closeCalendarPopupPage"
	    >
	      选择所选日期
	    </tn-button>
	  </view>
	</tn-popup>
	
	<tn-popup v-model="isShowInvoiceType" >
	    <view class="tn-p-lg popup-class">
			<view class="tn-p-sm tn-shadow tn-flex tn-border-bottom tn-gray-disabled_border">
				<view class="tn-w-3-4 " >
					发票属性
				</view>
			</view>
			<view class="tn-p-sm tn-shadow tn-flex">
				<tn-radio-group v-model="invoiceType">
					<!-- <tn-radio label="0">无</tn-radio> &nbsp;&nbsp;&nbsp;&nbsp; -->
					<tn-radio label="1">专票</tn-radio> &nbsp;&nbsp;&nbsp;&nbsp;
					<tn-radio label="2">普票</tn-radio>
				  </tn-radio-group>
			</view>
			
			<view class="tn-p-sm tn-shadow tn-flex tn-border-bottom tn-gray-disabled_border">
				<view class="tn-w-3-4" >
					备注
				</view>
			</view>
			<view class="tn-p-sm tn-shadow tn-flex">
				<tn-input
				    v-model="remark"
				    type="textarea"
				    placeholder="请输入备注"
				    height="180"
					:border = "false"
					confirm-type="done"
					:show-word-limit="true"
					:maxlength="200"
				  />
			</view>
			
			<view class="tn-pt-lg tn-flex justify-between">
				<view class="tn-w-1-3">
					<tn-button size="lg" type="danger" width="tn-w-1-3" @click="onClickInvoiceClose">取消</tn-button>
				</view>
				<view class="tn-w-1-3 tn-flex justify-end">
					<tn-button size="lg" type="success" width="tn-w-1-3" @click="onClickInvoiceSave">确定</tn-button>
				</view>	
			</view>
		</view>
	</tn-popup>
	
</template>

<script setup>
	import { ref,reactive,onMounted,nextTick  } from 'vue'
	import { postCall,postPay,postReturnPay  } from '@/api/index.js'
	import { EventBus } from '@/mitt/EventBus.js';
	import { toastMessage } from '@/utils/toast.js'
	import { createParams } from '@/utils/utils.js'
	import md5 from "js-md5";
	import dayjs from "dayjs";
	import { v4 as uuidv4 } from 'uuid';
	import Big from 'big.js';
	const procName = "PROC_APP_DO_ORDER";
	const selectDate = ref('')
	const searchValue = ref("")
	const currentSwiperIndex = ref(1)
	let currentTabsIndex = ref(0)
	const userInfo = reactive({});
	let index = 0;
	const showCalendarPopup = ref(false)
	const paging = ref(null)
	let tabsItem = ref('');
	const payConfig = {};
	const tmepItem = reactive({});
	const isShowInvoiceType = ref(false)
	const remark = ref('');
	
	let invoiceType = ref('2');
	
	let pageInfo = {
		P_PAGE : 1 ,
		P_PAGESIZE : 10
	}
	
	const queryList = (pageNo, pageSize) =>{
		pageInfo.P_PAGE = pageNo;
		pageInfo.P_PAGESIZE = pageSize;
		let params = {};
		params["P_PROC_NAME"] = "PROC_APP_DO_TMS";
		params["P_ACTION"] = "DONETMS";
		params["P_CON"] = searchValue.value;
		postCall(Object.assign(Object.assign(params,createParams(dataInfo)),pageInfo)).then(res=>{
			if(res){
				if(res.code===200 || res.code===1000){
							   // Object.assign(orderData,res.data.DATASET);	   
							   // console.log(statusData);
							   paging.value.complete(res.data.DATASET);
				}
			}
		  
		}).catch(res =>{
			paging.value.complete(false);
		})
	}
	
	const searchBtnClickEventPage = () =>{
		paging.value.reload();
	}
	
	const closeCalendarPopupPage = () =>{
		showCalendarPopup.value = false
		console.log(selectDate.value);
		let date = {
						"startDate":dayjs(selectDate.value[0]).format('YYYY-MM-DD'),
						"endDate":dayjs(selectDate.value[1]).format('YYYY-MM-DD')
					}
		 Object.assign(dataInfo,date);
		 paging.value.reload();
	}
	
	const clickOrderPage = (val) =>{
		index = val.id;
		paging.value.reload();
	}
	
	
	
	const openCalendarPopup = () => {
	  showCalendarPopup.value = true
	}
	
	
	
	const closeCalendarPopup = () => {
	  showCalendarPopup.value = false
	  console.log(selectDate.value);
	  let date = {
	  				"startDate":dayjs(selectDate.value[0]).format('YYYY-MM-DD'),
	  				"endDate":dayjs(selectDate.value[1]).format('YYYY-MM-DD')
	  			}
	   Object.assign(dataInfo,date);
	   doGetOrder();
	}
	
	const onClickClose = (item) =>{
		console.log(item.tradeid)
		if(item.tradeid){
			onLineReturn(item.tradeid,item.taxamount);
			
		}else{
			let params = {};
			params["P_PROC_NAME"] = procName;
			params["P_ACTION"] = "CLOSE";
			params["P_BILLNO"] = item.billno;
			postCall(params).then(res=>{
				if(res){
					if(res.code===200){
						toastMessage("作废成功！");
						paging.value.reload(); 
					}
				}
			})
		}
		
	}
	
	const onClickInvoiceType = (item) =>{
		isShowInvoiceType.value = true;
		Object.assign(tmepItem,item);
	}
	
	const onClickInvoiceSave = () =>{
		console.log(tmepItem);
		let params = {};
		params["P_PROC_NAME"] = "PROC_APP_DO_INVOICE";
		params["P_ACTION"] = "SAVE";
		params["P_INVOICETYPE"] = invoiceType.value;
		params["P_BILLCODE"] = tmepItem.billcode;
		params["P_TAXAMOUNT"] = tmepItem.taxamount;
		params["P_REMARK"] = remark.value;
		params["P_CLIENTID"] = tmepItem.clientid;
		postCall(params).then(res=>{
			if(res){
				if(res.code===200){
					isShowInvoiceType.value = false;
				}
			}
		})
		   
	}
	
	const onClickInvoiceClose = () =>{
		isShowInvoiceType.value = false;
	}
	
	const onClickInvoiceDown = (item) =>{
		uni.downloadFile({
		  url: item.invoiceurl,
		  success: function (res) {
		    var filePath = res.tempFilePath;
		    uni.openDocument({
		      filePath: filePath,
		      showMenu: true,
		      success: function (res) {
		        console.log('打开文档成功');
		      }
		    });
		  }
		});
	}
	const onClickPay = (item) =>{
		onLineWXPay(item.paytype,item.guid,item.businessname,item.taxamount)
	}
	
	const searchInputEvent = ()=>{
		
	}
	const searchBtnClickEvent = ()=>{
		
	}
	const dataInfo = reactive({"startDate":"2024-01-01","endDate":"2024-04-31"})
	let loginInfo = {};
	onMounted(()=>{
		loginInfo = uni.getStorageSync("LOGINUSER");
	
		const firstDayOfMonth = dayjs().startOf('month');
		let date = {
						"startDate":dayjs().subtract(1, 'day').format('YYYY-MM-DD'),
						"endDate":dayjs().format("YYYY-MM-DD")
					}
		Object.assign(dataInfo,date);
		
		Object.assign(userInfo,uni.getStorageSync('USERINFO'));
		
	})
	 

	
	const statusData = reactive([])
	const getStateInfo = () =>{
		
		let params = {};
		params["P_PROC_NAME"] = "PROC_APP_DO_MY";
		params["P_ACTION"] = "STATE";
		postCall(params).then(res=>{
			if(res){
				if(res.code===200){
					Object.assign(statusData,res.data.DATASET);	   
				}
			}
		})
		   
	}
	
	const clickOrder = (val) =>{
		index = val.id;
		// console.log(currentTabsIndex.value);
		doGetOrder();
	 //  uni.setStorageSync("order",val.id)	
	 //  uni.navigateTo({
		// url: val.path
	 //  });
	}
	const orderData = ref([]);
	
	
	
	const doGetOrder = (val) =>{
		
		console.log(currentTabsIndex.value);
		orderData.length = 0;
		let params = {};
		params["P_PROC_NAME"] = "PROC_APP_DO_ORDER";
		params["P_ACTION"] = index;
		postCall(Object.assign(params,createParams(dataInfo))).then(res=>{
			if(res){
				if(res.code===200){
							   Object.assign(orderData,res.data.DATASET);	   
							   // console.log(statusData);
				}
			}
		   
		})
	}
	
	let toNavigate = (val) =>{
		let tempOrderData  = [];
		let convertOrderData = [];
		let params = {};
		params["P_PROC_NAME"] = "PROC_APP_DO_TMS";
		params["P_ACTION"] = "DONEDETAIL";
		postCall(Object.assign(params,createParams(val)) ).then(res=>{
			if(res){
				if(res.code===200){
							   Object.assign(tempOrderData,res.data.DATASET);	   
							   const mergedData = tempOrderData.reduce((acc, cur) => {
							       const { businessname,twobusinessname, clientid,twoclientid,address,twoclientinfo,areaname,rfbillcode,paytype,billing,settledates, ...rest } = cur;
							       if (!acc[twoclientid]) {
							           acc[twoclientid] = { businessname,twobusinessname, clientid,twoclientid,address,twoclientinfo,areaname,rfbillcode,paytype,billing,settledates, details: [rest] };
							       } else {
							           acc[twoclientid].details.push(rest);
							       }
							       return acc; 
							   }, {});
							   
							   const businessStats = {};
							   for (const key in mergedData) {
							       const business = mergedData[key];
							       const totalPrice = business.details.reduce((total, item) => new Big(total).plus(new Big(item.sumtaxamount)) , 0);
										mergedData[key]["taxamount"] = totalPrice;
								   }
							    for (const key in mergedData) {
							   	    if (Object.hasOwnProperty.call(mergedData, key)) {
									   console.log(22);
									   convertOrderData.push(mergedData[key]);
									}
							     }
								uni.setStorageSync("TMSINFO",convertOrderData[0]) 
								uni.navigateTo({
									url: '/pages/delivery/donedeliverydetails'
								})
				}
			}
		   
		})
	}
	
	let doGetPayConfig = async () =>{
		let params = {};
		params["P_PROC_NAME"] = "PROC_APP_DO_SHOPPING";
		params["P_ACTION"] = "PAYCONFIG";		
		await postCall(params).then(res=>{
			if(res){
				if(res.code===200){
					Object.assign(payConfig,res.data.DATASET[0]);
					console.log(payConfig);
				}
			}
			
		})
	}
	
	let onLineReturn = async (oldtrxid,trxamt) =>{
		let guid = uuidv4();
		let params = {};
		params.cusid = payConfig.cusid;
		params.appid = payConfig.appid;
		params.version = "11";
		params.reqsn = guid;
		params.trxamt = (trxamt*100).toString();
		params.oldtrxid = oldtrxid;
		params.randomstr = guid;
		params.signtype = payConfig.signtype;
		await postReturnPay(params).then(res=>{
			if(res){
				if(res.code===200){d
					if(res.data.errmsg){
						toastMessage(res.data.errmsg)
					}
					if(res.data.trxstatus){
						if(res.data.trxstatus=="0000"){
							toastMessage("作废成功！");
						}
					}
				}
			}
		})
	}
	
	let onLineWXPay = (peyTypeValue,uuid,businessname,taxamount) =>{
		let params = {};
		params.cusid = payConfig.cusid;
		params.appid = payConfig.appid;
		params.version = payConfig.version;
		params.trxamt = parseFloat(new Big(taxamount).times(100)).toString(); // (shopClientInfoData.taxamount*100).toString();
		params.reqsn = uuid;
		params.notify_url = payConfig.notifyurl;
		params.body = businessname;
		params.remark = userInfo.staffid;
		if(peyTypeValue == 1){
			params.paytype = "W06";
		}else if(peyTypeValue == 2){
			params.paytype = "A02";
		}
		
		params.randomstr = uuid;
		params.signtype = payConfig.signtype;
		postPay(params).then(res=>{
			console.log(res);
			if(res){
				if(res.code===200){
					params.sign = res.data;
					console.log(params);
					var queryParams = [];
					for (var key in params) {
					  if (params.hasOwnProperty(key)) {
					    // var value = encodeURIComponent(params[key]);
						var value = params[key];
					    queryParams.push(key + "=" + value);
					  }
					}
					if(peyTypeValue==1){
						plus.share.getServices(res=>{
							let sweixin = '';
							for (var i = 0; i < res.length; i++) {
								let t = res[i];
								if (t.id == 'weixin') {
								  sweixin = t;
								}
							}
							console.log(sweixin)
							if(sweixin){
								sweixin.launchMiniProgram(
									{
										id: 'gh_e64a1a89a0ad',  // 要跳转小程序的原始ID
										path: 'pages/orderDetail/orderDetail'+"?"+queryParams.join("&"),  //  可带参数
										type: 0   // 微信小程序版本类型可取值： 0-正式版； 1-测试版； 2-体验版。 默认值为0。
									},
									// 目标小程序点击返回App后执行的回调，在此接收微信小程序传递的参数
									res2 => {
										console.log(typeof res2, res2)
										// res2是微信小程序传递回来的参数 类型为string 需转化为js对象使用
										let result = JSON.parse(res2)
										console.log(result) 
										// 拿到参数后执行你需要的逻辑    
										// ......   
									},
									  err2 => {
										console.log(err2)
									  }
									);
							}
						})
					} 
					if(peyTypeValue==2){
						 
						 let alipayUrl = null;
						 
						 if (uni.getSystemInfoSync().platform == "ios") {
							alipayUrl = 'alipay://platformapi/startapp?appId=2021001104615521';
						 }else{
							alipayUrl = 'alipays://platformapi/startapp?appId=2021001104615521';
						 }
						
						//alipayUrl 已经有? 问号了，所以这里需要进行编码
						// let params = encodeURIComponent('?'+queryParams.join("&"))
						const query = encodeURIComponent("payinfo=" + encodeURIComponent(JSON.stringify(params)));
						console.log(query);
						
						// page=pages/index/index  跳转到支付宝小程序页面的页面路径
						alipayUrl  = `${alipayUrl}&page=pages/orderDetail/orderDetail&thirdPartSchema=&query=${query}`
						console.log(alipayUrl);
						//唤起支付宝
						plus.runtime.openURL(alipayUrl);
						// window.location.href = alipayUrl;
					   //&thirdPartSchema=&query=${query}
						/*
						uni.navigateToAlipayMiniProgram({
						  appId: '2021001104615521',
						  path: `pages/orderDetail/orderDetail`, // 要打开的小程序页面路径
						  success: function() {
						    console.log('跳转到支付宝小程序成功');
						  },
						  fail: function(error) {
						    console.error('跳转到支付宝小程序失败', error);
						  }
						});
						*/
					}
				}else{
					toastMessage(res.msg);
				}
			}
			
		})
	}
	
</script>

<style>
.header-class{
	height: 17vh !important;
	flex-direction: column
}
.form-class{
	width: 90vw;
	margin-left: 5vw;
}
.button-class{
	margin-top: 5vh;
	width: 90vw;
	border-radius: 40px !important;
	/* color: #FFFFFF !important; */
	background: linear-gradient(to right,  #47e8be,#3379dc);
	/* border: 0px solid rgba(0, 0, 0, 0.2) !important; */
}

.button-class::after{
	border: 0px solid rgba(0, 0, 0, 0.2) !important;
}

.popup-calendar-button {
  margin: 0rpx 30rpx;
  width: calc(100% - 60rpx) !important;
  padding: 20rpx 30rpx !important;
}

.no-data-class{
	
	display: flex;
	justify-content: center;
	align-items: center;
	padding-top: 10vh;
}

.popup-class{
	/* width: 80vw; */
	/* height: 45vh !important; */
	/* text-align : center; */
	overflow-y: auto;
}
.calendar-class{
	/* height: 35vh; */
	height: 100% !important;
}
.uni-swiper-slides{
	height: 100% !important;
	width: 100% !important;
}

.tn-calendar__data{
	height: 35vh !important;
}
</style>
